<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
class Index extends Controller
{
    //登录页
    public function index()
    {
        return $this->fetch();
    }
    //处理登录
    public function login()
    {
        $data = [
            "user_phone"=>input('phone'),
            "user_pw"=>md5(input('pw')),
        ];
        // dump($data);
        // exit;
        $res = Db::name('user')->where($data)->find();
        // dump($res);
        // exit;
        if($res==null){
            return $this->error('账号密码错误');
        }else{
            Session::set("user_id",$res["user_id"]);
            $this->success('登录成功','home/index');
        }
    }
    //处理登录 用ajax方法
    public function login1()
    {
        $request = Request::instance();
        $post = $request->post();
        $data = [
            'user_phone' =>$_POST['phone'],
            'user_pw'=>md5($_POST['pw']),
            ];
        $validate = validate('Login');
        if(!$validate->check($data)){
            $msk = $validate->getError();
            $status =0;
            return json(['status'=>$status,'message'=>$msk]);
        }
        $res = Db::name('user')->where($data)->find();
        if($res==null){
            $status =0;
            $message = '账号或密码错误';
            return json(['status'=>$status,'message'=>$message]);
        }else{
            Session::set("user_id",$res["user_id"]);
            $status =1;
            $message = '登录成功';
            $url = 'http://localhost/yfz/public/index.php/index/home/index.html';
            return json(['status'=>$status,'message'=>$message ,'url'=>$url]);
        }
    }
    // 注册页
    public function reg()
    {
        return $this->fetch();
    }
    // 处理注册
    public function reg1()
    {
        $phone = input('phone');
        $data = [
            "phone"=>input('phone'),
            "pw"=>input('pw'),
            "pw1"=>input('pw1'),
        ];
        //验证数据
        $validate = validate('User');
        if(!$validate->check($data)){
            $msk = $validate->getError();
            $this->error($msk);
        }
        
        $data = [
            "user_phone"=>input('phone'),
            "user_pw"=>md5(input('pw')),
            "user_status" =>0,
            "user_time" =>date('Y-m-d H:i:s'),
        ];
        // dump($data);
        // exit;
        $res1 = Db::name('user')->where('user_phone',$phone)->find();
        if($res1 == null){
            $res = Db::name('user')->insert($data);
                if($res)
                {
                    return $this->success('注册成功','index/index');
                }
                else{
                    return  $this->error('失败，请重新填写信息');
                }
        }else{
            return  $this->error('手机号码已经注册');
        }
    }
    //注销功能
    public function logout(){
		Session::clear();
    	$this->redirect("index/index");
    }

}
